package com.springboot.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration
@MapperScan(basePackages = HisDatasourceConfig.PACKAGE,
	sqlSessionFactoryRef = "hisSqlSessionFactory")
public class HisDatasourceConfig {
	
	// hisdao扫描路径
	static final String PACKAGE = "com.springboot.hisdao"; 
	// mybatis mapper扫描路径
	static final String MAPPER_LOCATION = "classpath:mapper/his/*.xml";
	
	@Bean(name = "hisdatasource")
	@ConfigurationProperties("spring.datasource.druid.oracle2")
	public DataSource hisDataSource() {
		return DruidDataSourceBuilder.create().build();
	}
	
	@Bean(name = "hisTransactionManager")
    public DataSourceTransactionManager hisTransactionManager() {
        return new DataSourceTransactionManager(hisDataSource());
    }
 
    @Bean(name = "hisSqlSessionFactory")
    public SqlSessionFactory hisSqlSessionFactory(@Qualifier("hisdatasource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //如果不使用xml的方式配置mapper，则可以省去下面这行mapper location的配置。
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(HisDatasourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
